package com.roc.web.action.table;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.MerinfoTermBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.TerminalFlag;
import com.roc.web.action.count.ChangeCheckCountSearchCondition;
import com.roc.web.action.merinfo.MerinfoExportSearchCondtion;
import com.roc.util.constant.MerinfoStatus;

@Action
@Component
@Scope("prototype")
@Namespace("/merTerm")
public class MerinfoTermAction  extends PaginationBaseAction{
	
	/**
	 * file
	 * long:serialVersionUID:MerinfoTermAction.java
	 */
	
	private static final long serialVersionUID = 1L;
	private Logger logger=LogManager.getLogger(MerinfoTermAction.class);
	private MerinfoTermSearchCondtion  searchCondition;
	
	
	@Autowired
	private IPageService  pageService;
	
	@Autowired
	private IExcelService excelService;
	
	private ByteArrayInputStream excelFile;
	/**
	 * 跳往商终明细首页
	 * @Title: init
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年11月14日 上午10:03:14
	 *
	 */
	@Action(value="init",results={ @Result(name="success",location="/pages/table/merinfoTermDetail.jsp")})
	public String init(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode()) || op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;	   
		/*searchCondition = new MerinfoTermSearchCondtion();
		// 默认查询当天日期
		String today = Constance.currTime();
		
		searchCondition.setCrtMinDate(today);
		searchCondition.setCrtMaxDate(today);*/
		
	}
	
	/**
	 * 商终明细查询
	 * @Title: queryMerinfoTermList
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年11月14日 下午2:08:08
	 *
	 */
	@Action(value="queryMerinfoTermList",results={@Result(name="success",location="/pages/table/merinfoTermDetail.jsp")})
	public String queryMerinfoTermList(){
		
		
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode()) || op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
		if(searchCondition==null){
			searchCondition=(MerinfoTermSearchCondtion)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new MerinfoTermSearchCondtion();
			}
		}
		try {
			int rows = pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
				List<MerinfoTermBean> cclist=new ArrayList<MerinfoTermBean>();
				//查询
				dealWith(cclist,searchRsList);
			
			getRequest().setAttribute("cclist", cclist);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.info("查询商终明细数据异常："+e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
		addActionError("无权限访问!!!");
		return ERROR;	
	}
	
	
	/**
	 * 商终明细导出
	 * @Title: exportMerinfoTermDetail
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年11月14日 下午2:08:28
	 *
	 */
	@Action(value = "exportMerinfoTermDetail", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/table/merinfoTermDetail.jsp") })
	public String exportMerinfoTermDetail(){
		
		logger.info("导出商终明细excel开始");
		
		if(searchCondition==null){
			searchCondition=(MerinfoTermSearchCondtion)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new MerinfoTermSearchCondtion();
			}
		}
		try {
			
			int rows = pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<MerinfoTermBean> ccList=new ArrayList<MerinfoTermBean>();
			dealWith(ccList,searchRsList);
			logger.info("rows:" + rows + "    searchRsList.size():"+ searchRsList.size());
			HSSFWorkbook work=excelService.exportMerinfoTermList(ccList,searchCondition.getCrtMinDate(),searchCondition.getCrtMaxDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出商终明细计excel结束");
		} catch (Exception e) {
			logger.info("导出商终明细数据异常："+e);
		}
		return SUCCESS;
	}
	
	
	private List<MerinfoTermBean> dealWith(List<MerinfoTermBean> ccList,List<Object> searchRsList){
		StringBuffer sb = new StringBuffer();
		if(searchRsList!=null&&searchRsList.size()>0)
		{
			Iterator<?> iterator=searchRsList.iterator();
			while(iterator.hasNext())
			{
				Object[] obj=(Object[]) iterator.next();
				MerinfoTermBean mer=new MerinfoTermBean();
				mer.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				mer.setTermid(Constance.Null2EmptyTrim(obj[1]));
				mer.setTermStatus((TerminalFlag.getName(Constance.Null2EmptyTrim(obj[12])))); //终端状态
				mer.setName(Constance.Null2EmptyTrim(obj[3]));
				mer.setNameBusi(Constance.Null2EmptyTrim(obj[4]));
				//结算周期
				 if(!Constance.Null2EmptyTrim(obj[5]).equals("0")){
                     sb.append(Constance.Null2EmptyTrim(obj[5]));
                 }
                 if(!Constance.Null2EmptyTrim(obj[6]).equals("0")){
                     sb.append(Constance.Null2EmptyTrim(obj[6]));
                 }
                 if(!Constance.Null2EmptyTrim(obj[5]).equals("0") && !Constance.Null2EmptyTrim(obj[6]).equals("0") ){
                     sb.setLength(0);
                     sb.append(Constance.Null2EmptyTrim(obj[5])).append("/"+Constance.Null2EmptyTrim(obj[6]));
                 }
                 mer.setAccPeri(sb.toString());
				
				mer.setBusiLicnNo(Constance.Null2EmptyTrim(obj[7]));
				mer.setRegAddr(Constance.Null2EmptyTrim(obj[8]));
				mer.setInstalllocation(Constance.Null2EmptyTrim(obj[9]));
				mer.setCertif(Constance.Null2EmptyTrim(obj[10]));
				mer.setApprDate(Constance.Null2EmptyTrim(obj[11]));
				mer.setStatus(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[12])));	//商户状态
				mer.setDiscNorm(Constance.Null2EmptyTrim("无"));
				mer.setFilialeName(Constance.Null2EmptyTrim(obj[13]));
				mer.setCoopOrg(Constance.Null2EmptyTrim(obj[14]));
				mer.setRegion(Constance.Null2EmptyTrim(obj[15]));
				mer.setContactName(Constance.Null2EmptyTrim(obj[16]));
				mer.setContactPhoneno(Constance.Null2EmptyTrim(obj[17]));
				mer.setMccCd18(Constance.Null2EmptyTrim(obj[18]));
				mer.setMchtType(Constance.Null2EmptyTrim(obj[40]));   //mcc大类
				
				Map<String, String> Province = ConfigProperties.getGBProviceProperties();//省份map
				mer.setProv(Province.get(Constance.Null2EmptyTrim(obj[19])));//省
				Map<String, String> city =ConfigProperties.getGBCityProperties(Constance.Null2EmptyTrim(obj[19]));
				if(city.size()>0){
					mer.setCity(Constance.Null2EmptyTrim(city.get(obj[20])));    //市
				}
				
				mer.setExt1(Constance.Null2EmptyTrim(obj[21]));   //发展人
				mer.setTermAut(Constance.Null2EmptyTrim("免投"));  //机具产权
				mer.setTermTp(Constance.Null2EmptyTrim(obj[22]));  
				mer.setDeviceCd(Constance.Null2EmptyTrim(obj[23]));
				mer.setProposer(Constance.Null2EmptyTrim(obj[24]));
				mer.setBusi_main(Constance.Null2EmptyTrim(obj[25]));
				mer.setREC_CRT_TS(Constance.Null2EmptyTrim(obj[26]));
				if("4".equals(Constance.Null2EmptyTrim(obj[12]))){
					mer.setTermShutDate(Constance.Null2EmptyTrim(obj[39]));
				}else{
					mer.setTermShutDate(Constance.Null2EmptyTrim("无"));
				}
				mer.setT1_J(Constance.Null2EmptyTrim(obj[27]));
				mer.setT1_JF(Constance.Null2EmptyTrim(obj[28]));
				mer.setT1_D(Constance.Null2EmptyTrim(obj[29]));
				mer.setT1_DF(Constance.Null2EmptyTrim("0.0"));
				mer.setZFB_S(Constance.Null2EmptyTrim(obj[37]));
				mer.setYL_S(Constance.Null2EmptyTrim(obj[38]));
				 if(!Constance.Null2EmptyTrim(obj[6]).equals("0")){
					 mer.setD0Status(Constance.Null2EmptyTrim("正常"));
				 }else{
					 mer.setD0Status(Constance.Null2EmptyTrim("未开通"));
				 }
				mer.setD0_J(Constance.Null2EmptyTrim(obj[30]));
				mer.setD0_D(Constance.Null2EmptyTrim(obj[31]));
				mer.setApprovalusername(Constance.Null2EmptyTrim(obj[32]));
				mer.setBackName(Constance.Null2EmptyTrim(obj[33]));
				mer.setAccount(Constance.Null2EmptyTrim(obj[34]));
				mer.setBankNa(Constance.Null2EmptyTrim(obj[35]));   //银行名字
				mer.setBankName(Constance.Null2EmptyTrim(obj[35]));//支行名称
				mer.setExtraRate(Constance.Null2EmptyTrim("标准"));
				mer.setIsYsq(Constance.Null2EmptyTrim(obj[36]));
				/*mer.setDJmax(Constance.Null2EmptyTrim(obj[0]));
				mer.setDDmax(Constance.Null2EmptyTrim(obj[0]));
				mer.setDSmax(Constance.Null2EmptyTrim(obj[0]));*/
				 sb.setLength(0);
				ccList.add(mer);
			}
		}
		return ccList;
	}


	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_MERINFO_TERM_DETAIL, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (MerinfoTermSearchCondtion)getSession().getAttribute(SEARCH_SESSION_MERINFO_TERM_DETAIL);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	
	public MerinfoTermSearchCondtion getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(MerinfoTermSearchCondtion searchCondition) {
		this.searchCondition = searchCondition;
	}


	public ByteArrayInputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(ByteArrayInputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName = "商终明细信息统计" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

	
	
	
}
